import {
  defineStore,
  storeToRefs
} from "pinia";
import api from "@/api";
import {
  util,
  mergeGoods
} from "@/pages/shopping/cart/util/util.js";
import {
  getPresalesDelivery,
  handleShoppingCartParams,
} from "@/pages/shopping/cart/util/cart.js";
import BigNumber from "bignumber.js"; // 浮点数运算插件
import {
  loginStatus
} from "@/hooks/useLogin";
import {
  useUserStoreToRefs
} from "@/store/useUserStore";
import {
  useOrderStoreToRefs
} from "@/store/useOrderStore";

var brandsRefereeList = [];

export const useCartStore = defineStore("cart", {
  state: () => ({
    brandSaleList: [], //即将开售商品
    brandInvalidList: [], //失效列表
    brandCartList: [], //商品列表
    brandOrderList: [], //下单列表
    orderCouponData: [], // 订单可使用优惠券列表
    len: 0,
    runshengLen: 0,
    addressList: [],
  }),
  actions: {
    //订单可使用优惠券列表
    GET_COUPON_LIST(value) {
      this.orderCouponData = value;
    },
    //下单携带商品
    GET_ORDER_LIST(value) {
      this.brandOrderList = value;
    },
    // 储存预售商品
    GET_SALE_LIST(value) {
      this.brandSaleList = value;
    },
    //储存失效商品
    GET_INVALID_LIST(value) {
      this.brandInvalidList = value;
    },
    // 储存购物车数量
    GET_CART_LIST(value) {
      this.brandCartList = value;
      this.GET_LEN(value);
    },
    GET_LEN(value) {
      let arr = value.reduce((pre, cur) => {
        return pre.concat(cur.shoppingCarVOlist);
      }, []);
      const length = arr.reduce((pre, cur) => {
        return pre + Number(cur.amount);
      }, 0);

      this.runshengLen = length;
    },
    // 清除购物车数据
    clearCartData() {
      this.GET_SALE_LIST([]);
      this.GET_INVALID_LIST([]);
      this.GET_CART_LIST([]);
    },
    // 进来时获取购物车数量
    async getGartList(msg) {
      const {
        userInfo
      } = useUserStoreToRefs();
      console.log("getGartList");
      // uni.showLoading({
      // 	mask:true
      // });
      return new Promise(async (resolve, rej) => {
        if (loginStatus()) {
          //登录时获取购物车列表
          let res;
          const params = {
            brandId: "",
          };
          res = await api({
            method: "get",
            url: `/mall/shopping/goods/v2/car`,
          });
          res = res.data;
          console.log("购物车数据", res);
          if (res.length <= 0) {
            this.GET_SALE_LIST([]);
            this.GET_INVALID_LIST([]);
            this.GET_CART_LIST([]);
            uni.hideLoading();
            resolve([]);
            return null;
          }
          let resData = res;

          let data = {
            data: resData,
            userInfo: userInfo,
          };
          var res2 = await getNewProductMsg(data);
          let arr = []; //失效商品
          let arr2 = []; //预售商品
          let arr3 = []; //有效商品
          // //筛选失效商品 已下架 限购人群 数量超出 售罄 商品被删除 规格不存在
          console.log("res21111111111", res2);
          res2.forEach((item, i) => {
            item.shoppingCarVOlist.forEach((itemChild, j) => {
              if (
                itemChild.status == 2 ||
                itemChild.isError1 ||
                itemChild.isError2 ||
                (itemChild.stocks == 0 && itemChild.prepareStocks == 0) ||
                itemChild.delFlag == 1 ||
                itemChild.skuStatus == 0 ||
                itemChild.skuDelFlag == 1 ||
                itemChild.oneBuyPromotionVO
              ) {
                arr.push(itemChild);
              } else if (itemChild.status == 0) {
                //单独列出的预售
                arr2.push(itemChild);
              } else {
                arr3.push(itemChild);
              }
            });
          });
          //排列有效商品
          let arr3List = [];
          arr3.forEach((item, i) => {
            if (arr3List.length <= 0) {
              let obj = {
                brandsName: item.brandsName,
                haveCoupon: item.haveCoupon,
                maxDiscountCoupon: item.maxDiscountCoupon,
                shoppingCarVOlist: [item],
              };
              arr3List.push(obj);
            } else {
              let obj = {
                brandsName: item.brandsName,
                haveCoupon: item.haveCoupon,
                maxDiscountCoupon: item.maxDiscountCoupon,
                shoppingCarVOlist: [item],
              };
              arr3List.push(obj);
            }
          });
          arr3List.forEach((item) => {
            item.radio = true;
            item.shoppingCarVOlist.forEach((citem) => {
              citem.radio = citem.isSelect ? true : false;
              item.brandsId = citem.brandsId;
              citem.discountPrice = "0.00";
              if (!citem.radio) {
                item.radio = false;
              }
              const count = new BigNumber(citem.price)
                .times(citem.amount)
                .toNumber(); // 计算总价
              if (citem.radio && citem.discountMoney != count) {
                // citem.discountPrice = (
                //   citem.price -
                //   Number(citem.discountMoney || 0).div(citem.amount)
                // ).toFixed(2);
                citem.discountPrice = new BigNumber(citem.price)
                  .minus(citem.discountMoney || 0)
                  .div(citem.amount)
                  .toFixed(2);
              }
            });
          });
          this.GET_SALE_LIST(arr2);
          this.GET_INVALID_LIST(arr);
          this.GET_CART_LIST(arr3List);
          console.log("arr3List", arr3List);
          resolve(arr3List);
        } else {
          this.GET_SALE_LIST([]);
          this.GET_INVALID_LIST([]);
          this.GET_CART_LIST([]);
          resolve([]);
        }
        uni.hideLoading();
      });
    },
    //添加购物车
    async getAddCard(msg) {
      const {
        userInfo
      } = useUserStoreToRefs();
      // const msg = {
      // 	addType:4, 购物车操作类型
      // 	arr:this.brandCartList, 操作的数据
      // 	arrType:2,数据是否嵌套
      // 	ifRadio:true,是否需要判断勾选
      //  isSelect:true,根据购物车显示选中与否，false表示加入及选中
      // };
      console.log("getAddCard", msg);
      console.log("msg arr", msg.arr);
      console.log("msg arr", msg.arr.value);
      let params = {
        storeId: msg.storeId,
        goodsType: msg.goodsType,
        addType: msg.addType,
        shoppingCarList: [],
        tag: msg.tag, // 通过tag区分 cagaba 0  1 门店下单
      };
      switch (msg.arrType) {
        case 1: //单成数据
          msg.arr.forEach((item) => {
            params.shoppingCarList.push({
              id: item.id,
              amount: item.amount,
              isLettering: item.isLettering,
              letteringMsg: item.letteringMsg,
              skuCode: item.skuCode,
              removeSkuCode: item.removeSkuCode,
              isSelect: msg.isSelect ? (item.radio ? 1 : 0) : 1,
              refereeId: msg.addType == 1 ? userInfo.id : "",
            });
          });
          break;
        case 2: //确认订单多嵌套数据
          msg.arr.forEach((item) => {
            if (!item.shoppingCarVOlist) {
              item.shoppingCarVOlist = item.shopData;
            }

            item.shoppingCarVOlist.forEach((itemChild) => {
              params.shoppingCarList.push({
                id: itemChild.id,
                amount: itemChild.amount,
                isLettering: itemChild.isLettering,
                letteringMsg: itemChild.letteringMsg,
                skuCode: itemChild.skuCode,
                removeSkuCode: item.removeSkuCode,
                isSelect: msg.isSelect ? (itemChild.radio ? 1 : 0) : 1,
                refereeId: msg.addType == 1 ? userInfo.id : "",
              });
            });
          });
          break;
      }

      console.log(msg);

      // 	var res = await api({
      // 		method: "POST",
      // 		url: `/goods/car`,
      // 		data: params,
      // 	  });
      //   }

      // ctgaba加入购物车 和 润生门店点餐和产品加入购物车，tag有值就是润生门店普通购买
      var res = await api({
        method: "POST",
        url: `/mall/shopping/goods/car`,
        data: params,
      });
      res = res.data;

      if (msg.addType == 1) {
        this.len = this.len + params.shoppingCarList[0].amount;
      } else {
        this.GET_LEN(this.brandCartList);
      }

      return res;
    },
    //拆分订单-处理确认订单里的商品
    async getOrderList(params) {
      const {
        addressInfo
      } = useOrderStoreToRefs();
      return new Promise(async (resolve, reject) => {
		uni.setStorageSync("product_info", params);
        const deliveryWay = params[0].deliveryWay || 0;
        uni.setStorageSync("storage_orderNum", false);
        //当地址为空的时候先请求地址
        if (this.addressList.length <= 0) {
          // await dispatch("getAddress");
        }
        //saleChannel 0普通 1积分 2农场

        //普通0 和 门店普通商品 4
        if (params[0].saleChannel == 0 || params[0].saleChannel == 4) {
          let old = [];

          // 合并相同商品
          params = mergeGoods(
            params,
            (single, repeat) => {
              if (single.skuCode == repeat.skuCode) {
                single.amount += Number(repeat.amount);
                return true;
              }
            },
            "skuCode"
          );
          if (this.brandOrderList.length > 0) {
            old = util.deepClone(this.brandOrderList);
          }
          const {
            userInfo
          } = useUserStoreToRefs();
          var newProductMsg = await getNewProductMsg({
            data: params,
            userInfo: userInfo,
            isSelect: 1,
            comboRefereeId: "",
          });
          // commit('GET_COUPON_LIST', newProductMsg)

          params = newProductMsg.reduce((pre, cur) => {
            return pre.concat(cur.shoppingCarVOlist);
          }, []);

          //获取最新运费
          const paramsFreight = {};
          let productArr = [];
          let res2 = {};
          let arrFrei = [];
          var sequentialOrderList = [];
          params.forEach((item, index) => {
            // paramsOfExpress.forEach((item, index) => {
            productArr[index] = {};
            productArr[index].goodsId = item.id; // 产品ID
            productArr[index].name = item.name ? item.name : item.goodsName; // 商品名称
            productArr[index].price = item.price; // 市场价格
            productArr[index].count = item.amount; // 数量
            productArr[index].weight = item.weight; // 净重量（g）
            productArr[index].deliverWeight = item.deliverWeight; //发货重量（连包装的重量，g）
            productArr[index].packageBoxWeight = item.packageBoxWeight; //发货（单个）箱子重量（g)
            productArr[index].ifDeliverAlone = item.ifDeliverAlone; // 是否产品独立发货：0-否，1-是
            productArr[index].packageLimit = item.packageLimit; // 产品装箱上限
            productArr[index].ifInsurance = item.ifInsurance; // 是否保价：0-否，1-是
            productArr[index].specifyExpress = item.specifyExpress; // 指定快递(空-不指定，其他-服务商名称)
            productArr[index].expressFeeTemplateId = item.logisticsTemplateId; //快递计费模板id
            productArr[index].brandsId = item.brandsId;
            productArr[index].presellOn =
              item.saleType == 3 ||
              (item.stocks == 0 && item.saleType == 2) ||
              (item.stocks == 0 && item.prepareStocks > 0) ?
              1 :
              0; //1 预售  0 非预售
            productArr[index].deliverVolume = item.deliverVolume; //发货体积
            productArr[index].skuCode = item.skuCode;
            if (item.isLettering == 1 && item.letteringMsg) {
              productArr[index].isLettering = 1;
            } else {
              productArr[index].isLettering = 0;
            }
          });
          paramsFreight["addressId"] = "";
          paramsFreight["productArr"] = encodeURIComponent(
            JSON.stringify(productArr)
          );

          // 获取订单拆分结构
          try {
            // sequentialOrderList = await splitOrders({
            // 	...paramsFreight,
            // 	deliveryWay,
            //   })
            sequentialOrderList = await api({
              method: "post",
              url: `/mall/order/V2021/getSplitOrders`,
              data: {
                ...paramsFreight,
                deliveryWay,
              },
            }).then((res) => {
              return res || [];
            });
          } catch (e) {
            return reject();
          }
          sequentialOrderList = sequentialOrderList.data || [];

          // 将拆分的订单数据添加状态标识——商品中有现货和预售混合时，将两者分开
          sequentialOrderList.forEach((item, index) => {
            item.orderGoodsDTOS.forEach((goodItem, goodIndex) => {
              item.orderGoodsDTOS[goodIndex] = productStatus(goodItem);
            });
          });
          // 计算运费
          if (this.addressList.length > 0) {
            paramsFreight["addressId"] = addressInfo.id;

            // 获取运费
            try {
              //   res2 = await getFreight({
              //     ...paramsFreight,
              //     deliveryWay,
              //   });
              res2 = await api({
                method: "POST",
                url: `/order/V2021/v2/freight`,
                data: {
                  ...paramsFreight,
                  deliveryWay,
                },
              });
              res2 = res2.data;
            } catch (e) {
              return reject();
            }

            res2.forEach((item) => {
              item.skuList.forEach((citem, i) => {
                let chi = JSON.parse(JSON.stringify(item));
                chi.skuCode = citem;
                if (i > 0) {
                  chi.freights = "0.00";
                  chi.originalFreight = "0.00";
                }
                arrFrei.push(chi);
              });
            });
          }

          if (arrFrei.length > 0) {
            params.forEach((item) => {
              arrFrei.forEach((citem) => {
                let isLettering = Boolean(item.isLettering && item.letteringMsg) ?
                  1 :
                  0;
                // let isLettering = item.isLettering
                let presellOn =
                  item.saleType == 3 ||
                  (item.stocks == 0 && item.saleType == 2) ||
                  (item.stocks == 0 && item.prepareStocks > 0) ?
                  1 :
                  0;
                if (
                  item.brandsId == citem.brandsId &&
                  (presellOn == 1 && citem.presellOn == 1 ?
                    true :
                    isLettering == citem.isLettering) &&
                  presellOn == citem.presellOn &&
                  item.skuCode == citem.skuCode
                ) {
                  item.freights = citem.freights;
                  item.originalFreight = citem.originalFreight;
                }
              });
            });
          } else {
            params.forEach((item) => {
              item.freights = "0.00";
              item.originalFreight = "0.00";
            });
          }

          let brandsList = [];
          let len = params.length;

          //拆分订单-先分出同一品牌下的刻字属性商品和普通商品
          for (let l = 0; l < len; l++) {
            if (params[l].oneBuyPromotionVO && params[l].oneBuyPromotionVO.id) {
              params[l].price = params[l].oneBuyPromotionVO.price;
            }
            const goodsItem = {
              isLettering: Boolean(
                  params[l].isLettering && params[l].letteringMsg
                ) ?
                1 :
                0,
              presellOn: params[l].saleType == 3 ||
                (params[l].stocks == 0 && params[l].saleType == 2) ||
                (params[l].stocks == 0 && params[l].prepareStocks > 0) ?
                1 :
                0,
              goodsId: params[l].id,
              shopremarks: "",
            };
            params[l] = {
              ...params[l],
              ...goodsItem,
            };
          }
          // 拆分开始
          sequentialOrderList.forEach((item) => {
            item.orderGoodsDTOS.forEach((orderGoodsItem, orderGoodsIndex) => {
              const goodInfo =
                params.find((goodItem) => {
                  return goodItem.skuCode == orderGoodsItem.skuCode;
                }) || {};

              // 合并对象，相同属性合并时，值为空则不覆盖
              function mergeRules(objValue, srcValue) {
                return objValue == null ? srcValue : objValue;
              }
              var mergeObejct = customPartialRight(
                customAssignInWith,
                mergeRules
              );

              item.orderGoodsDTOS[orderGoodsIndex] = mergeObejct(
                orderGoodsItem,
                goodInfo
              );
              item.orderGoodsDTOS[orderGoodsIndex].amount =
                orderGoodsItem.count;
            });
            item.shopData = item.orderGoodsDTOS;
          });
          // 拆分结束

          // 配备模板渲染所需要的数据
          sequentialOrderList[0] = {
            ...sequentialOrderList[0],
            ...((sequentialOrderList[0] &&
              sequentialOrderList[0].orderGoodsDTOS &&
              sequentialOrderList[0].orderGoodsDTOS[0]) || {}),
          };
          brandsList = sequentialOrderList;

          brandsList[0].all_price = 0;
          brandsList[0].all_freightprice = 0;
          brandsList[0].all_subtotalPrice = 0;
          brandsList[0].all_originalFreight = 0;
          // 匹配运费 , 总额  小计等
          brandsList.forEach((citem, i) => {
            // 运费
            citem.freightPrice = citem.shopData.reduce((pre, cur) => {
              return pre + Number(cur.freights || 0);
            }, 0);
            citem.freightPrice = citem.freightPrice.toFixed(2);
            //原运费
            citem.originalFreightTeam = citem.shopData.reduce((pre, cur) => {
              return pre + Number(cur.originalFreight || 0);
            }, 0);
            citem.originalFreightTeam = citem.originalFreightTeam.toFixed(2);
            // 品牌下的商品总额
            citem.price = citem.shopData.reduce((pre, cur) => {
              return pre + Number(cur.amount) * Number(cur.price);
            }, 0);

            citem.price = citem.price.toFixed(2);
            //品牌下的商品小计
            citem.subtotalPrice =
              Number(citem.price) +
              Number(!citem.freightPrice ? 0 : citem.freightPrice);
            citem.subtotalPrice = citem.subtotalPrice.toFixed(2);

            // 所有商品总费用
            brandsList[0].all_price += Number(brandsList[i].price);
            // 所有商品总运费
            // brandsList[0].all_freightprice += Number(brandsList[i].freightPrice ==
            // 	undefined ? 0 : brandsList[i].freightPrice)
            // 所有商品原始总运费
            // brandsList[0].all_originalFreight += Number(brandsList[i].originalFreightTeam ==undefined ? 0 : brandsList[i].originalFreightTeam)
          });
          //所有商品总运费
          if (this.addressList.length > 0 && params[0].saleChannel != 4) {
            res2.forEach((item) => {
              brandsList[0].all_freightprice += Number(item.freights);
              // 所有商品原始总运费
              brandsList[0].all_originalFreight += Number(
                item.originalFreight || 0
              );
            });
          }
          brandsList[0].brandsRefereeList = brandsRefereeList;
          brandsList[0].all_freightprice =
            brandsList[0].all_freightprice.toFixed(2);
          // 所有商品总计
          brandsList[0].all_subtotalPrice = (
            Number(brandsList[0].all_price) +
            Number(brandsList[0].all_freightprice)
          ).toFixed(2);

          brandsList[0].all_price = brandsList[0].all_price.toFixed(2);
          brandsList[0].all_originalFreight =
            brandsList[0].all_originalFreight.toFixed(2);

          // brandsList[0].tax = "0.00"
          // brandsList[0].feeDesUrl = tax.feeDesUrl;
          //赋值备注
          if (old.length > 0) {
            brandsList.forEach((item, i) => {
              item.shopremarks = (old[i] && old[i].shopremarks) || "";
            });
          }
          // commit("GET_ORDER_LIST", brandsList);
          // commit("GET_COUPON_LIST", newProductMsg);
          this.GET_ORDER_LIST(brandsList);
          this.GET_COUPON_LIST(newProductMsg);
          resolve(true);
        }
      }).catch((err) => {
        // 如果购物车到确认订单页面之中被下架，接口无法执行下去时，根据当前页面是否为确认订单页进行返回和刷新
        uni.showToast({
          icon: "none",
          title: err,
        });

        let pages = getCurrentPages();
        let currentPage = pages[pages.length - 1] || {};
        let currentRoute = currentPage.route;
        let fullPath = currentPage.__page__.fullPath;
        setTimeout(() => {
          if (
            currentRoute.indexOf &&
            currentRoute.indexOf("confirmOrder") > -1
          ) {
            uni.navigateBack();
          } else {
            uni.redirectTo({
              url: fullPath,
            });
          }
        }, 2000);
        return Promise.reject(err);
      });
    },

    check(params) {
      return new Promise(async (resolve, reject) => {
        resolve(productStatus(params));
      });
    },
  },
  persist: {
    storage: {
      getItem: (key) => uni.getStorageSync(key),
      setItem: (key, value) => uni.setStorageSync(key, value),
    },
  },
});

export const useCartStoreToRefs = () => {
  return storeToRefs(useCartStore());
};

export const resetUseCartStore = () => {
  useCartStore().$reset();
};

//更新商品
//isSelect 在确认订单时传 1,表示默认为勾选状态
//comboRefereeId 分享商品的推荐人ID
async function getNewProductMsg(msgInfo) {
  let {
    data,
    userInfo,
    subUserId,
    isSelect,
    comboRefereeId
  } = msgInfo;
  const params = handleShoppingCartParams(
    data,
    userInfo,
    subUserId,
    isSelect,
    comboRefereeId
  );
  //处理从购物车列表获取的数据
  var res2 = await api({
    method: "PUT",
    url: `/mall/shopping/goods/V2021/v3/shopping-car`,
    data: JSON.stringify(params),
  });
  res2 = res2.data;
  console.log("res2", res2);
  //整理商品类型
  if (res2.length > 0) {
    brandsRefereeList = res2[0].brandsRefereeList;
    res2.forEach((item) => {
      item.shoppingCarVOlist.forEach((itemChild) => {
        itemChild.haveCoupon = item.haveCoupon;
        itemChild.maxDiscountCoupon = item.maxDiscountCoupon;
        itemChild = productStatus(itemChild);
      });
    });
  }
  return res2;
}

function productStatus(itemChild) {
  //判断预售时间是否到期
  if (itemChild.status == 0 && itemChild.saleTime) {
    let curTime = new Date().getTime();
    itemChild.saleTime = itemChild.saleTime.replace(/\-/g, "/");
    let endTime = new Date(itemChild.saleTime).getTime();
    if (endTime <= curTime) {
      itemChild.status = null;
    }
  }

  if (itemChild.oneBuyPromotionVO) {
    const infoData = itemChild.oneBuyPromotionVO;
    let startTimestamp = timeStamp(infoData.startTime); //活动开始时间戳
    let endTimestamp = timeStamp(infoData.endTime); //活动结束时间戳
    let nowTimestamp = new Date().getTime(); //获取当前时间戳
    if (
      infoData.status == 0 ||
      (infoData.status == 1 && nowTimestamp < startTimestamp)
    ) {
      // 一元购活动未开始
      itemChild.openStatus1 = "未开始";
      itemChild.openColor1 = "#F29582";
    }
    if (
      infoData.status == 1 &&
      nowTimestamp >= startTimestamp &&
      nowTimestamp <= endTimestamp
    ) {
      // 一元购活动在有效期
      itemChild.openStatus1 = "抢购中";
      itemChild.openColor1 = "#DD1624";
    }
    if (
      infoData.status == 2 ||
      (infoData.status == 1 && nowTimestamp > endTimestamp)
    ) {
      // 一元购活动已结束
      itemChild.openStatus1 = "已结束";
      itemChild.openColor1 = "#999";
    }
  }
  // if (itemChild.oneBuyPromotionVO) {
  // 	itemChild.openStatus1 = "抢购中"
  // 	itemChild.openColor1 = "#DD1624"
  // }

  if (itemChild.status == 0) {
    itemChild.openStatus2 = "即将开售";
    itemChild.openColor2 = "#FF4C4E";
    itemChild.isPredict = true; //外部处理倒计时
    itemChild.disabled = true;
  }
  if (
    itemChild.saleType == 3 ||
    (itemChild.stocks == 0 && itemChild.saleType == 2) ||
    (itemChild.stocks == 0 && itemChild.prepareStocks > 0) ||
    itemChild.presellOn == 1
  ) {
    itemChild.openStatus3 = "预售";
    itemChild.openColor3 = "#FF4C4E";
    const presalesDelivery = getPresalesDelivery(itemChild);
    itemChild.isPredict =
      itemChild.deliveryTimeType == 0 ?
      presalesDelivery :
      `${itemChild.deliveryMsg}`;
  }
  //运营在后台删除了商品
  if (itemChild.delFlag == 1) {
    itemChild.invalidIntro = "规格不存在";
    return itemChild;
  }
  //商品下架
  if (itemChild.status == 2) {
    itemChild.invalidIntro = "商品已下架";
    return itemChild;
  }
  // 售卖完毕
  if (itemChild.stocks == 0 && itemChild.prepareStocks == 0) {
    itemChild.invalidStatus = false;
    itemChild.sellOut = true;
    itemChild.disabled = true;
    itemChild.invalidIntro = "商品已抢光";
    return itemChild;
  }
  //规格禁用
  if (itemChild.skuStatus == 0 || itemChild.skuDelFlag == 1) {
    itemChild.invalidIntro = "规格不存在";
    return itemChild;
  }
  if (itemChild.oneBuyPromotionVO) {
    itemChild.invalidIntro = "价格已失效";
    return itemChild;
  }
  // 为1时表示刻字
  if (itemChild.isLettering == 1) {}
  //是否已达购买数量
  if (getLimitStatus(itemChild)) {
    itemChild.isError2 = true;
    itemChild.errorMessag =
      getLimitTime(
        itemChild.purchaseLimitType,
        itemChild.purchaseLimitRules,
        1
      ) +
      (itemChild.alreadyBuyNum ?
        `(已购${itemChild.alreadyBuyNum ? itemChild.alreadyBuyNum : "0"}件)` :
        "");

    itemChild.invalidIntro = "已购数量已达限购上限";
    return itemChild;
  }

  return itemChild;
}

function getLimitStatus(product) {
  //限购数量是否超标
  if (product.purchaseLimitType == 0 || product.isLimit == 1) {
    return false;
  }

  if (product.purchaseLimitType) {
    var num =
      product.purchaseLimitType == 1 ?
      Number(product.purchaseLimitRules.split(",")[1]) :
      Number(product.purchaseLimitRules);
    var syNum =
      product.purchaseLimitType >= 1 ?
      num -
      Number(product.alreadyBuyNum == null ? 0 : product.alreadyBuyNum) :
      "";
    return product.purchaseLimitType != 0 && syNum <= 0;
  }
}

//purchaseLimitType 0不限购 1按时间限购 2永久限购
function getLimitTime(purchaseLimitType, purchaseLimitRules, type) {
  if (purchaseLimitType != 0) {
    if (purchaseLimitType == 1) {
      var arr = purchaseLimitRules.split(",");
    }
    var num = purchaseLimitType == "1" ? arr[1] : purchaseLimitRules;
    if (purchaseLimitType == 1) {
      if (arr[0] == 7) {
        var day = "每周";
      } else if (arr[0] == 1) {
        var day = "每天";
      } else {
        var day = "每月";
      }
    } else {
      var day = ""; //永久
    }
    if (type == 1) {
      return day + "限购" + num + "件";
    }
  }
}

//时间转换成时间戳
function timeStamp(date) {
  return (
    new Date(date.replace(/-/g, "/")).getTime() || new Date(date).getTime()
  );
}

function customAssignInWith(target, ...sources) {
  const customizer =
    typeof sources[sources.length - 1] === "function" ?
    sources.pop() :
    undefined;

  sources.forEach((source) => {
    if (source === null || source === undefined) {
      return;
    }

    // 遍历源对象的所有可枚举属性，包括原型链上的属性
    for (let key in source) {
      if (
        Object.prototype.hasOwnProperty.call(source, key) ||
        source[key] !== undefined
      ) {
        const targetValue = target[key];
        const sourceValue = source[key];

        if (customizer) {
          const result = customizer(
            targetValue,
            sourceValue,
            key,
            target,
            source
          );
          if (result !== undefined) {
            target[key] = result;
            continue;
          }
        }

        if (sourceValue !== undefined) {
          target[key] = sourceValue;
        }
      }
    }
  });

  return target;
}

function customPartialRight(func, ...partials) {
  return function (...args) {
    const newArgs = [...args, ...partials];
    return func.apply(this, newArgs);
  };
}